[[...path]].page.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import React from 'react';
  2. import { IUserHasId, IPagePopulatedToShowRevision } from '@growi/core';
  3. import {
  4. GetServerSideProps, GetServerSidePropsContext,
  5. } from 'next';
  6. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  7. import dynamic from 'next/dynamic';
  8. import Head from 'next/head';
  9. import superjson from 'superjson';
  10. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  11. import { MainPane } from '~/components/Layout/MainPane';
  12. import { ShareLinkLayout } from '~/components/Layout/ShareLinkLayout';
  13. import GrowiContextualSubNavigationSubstance from '~/components/Navbar/GrowiContextualSubNavigation';
  14. import RevisionRenderer from '~/components/Page/RevisionRenderer';
  15. import ShareLinkAlert from '~/components/Page/ShareLinkAlert';
  16. import type { PageSideContentsProps } from '~/components/PageSideContents';
  17. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  18. import type { ShareLinkPageContentsProps } from '~/components/ShareLink/ShareLinkPageContents';
  19. import { SupportedAction, SupportedActionType } from '~/interfaces/activity';
  20. import { CrowiRequest } from '~/interfaces/crowi-request';
  21. import { RendererConfig } from '~/interfaces/services/renderer';
  22. import { IShareLinkHasId } from '~/interfaces/share-link';
  23. import type { PageDocument } from '~/server/models/page';
  24. import { generateSSRViewOptions } from '~/services/renderer/renderer';
  25. import {
  26. useCurrentUser, useCurrentPageId, useRendererConfig, useIsSearchPage, useCurrentPathname,
  27. useShareLinkId, useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsSearchScopeChildrenAsDefault, useDrawioUri, useIsContainerFluid,
  28. } from '~/stores/context';
  29. import loggerFactory from '~/utils/logger';
  30. import { NextPageWithLayout } from '../_app.page';
  31. import {
  32. CommonProps, getServerSideCommonProps, generateCustomTitleForPage, getNextI18NextConfig,
  33. } from '../utils/commons';
  34. const logger = loggerFactory('growi:next-page:share');
  35. const PageSideContents = dynamic<PageSideContentsProps>(() => import('~/components/PageSideContents').then(mod => mod.PageSideContents), { ssr: false });
  36. // const Comments = dynamic(() => import('~/components/Comments').then(mod => mod.Comments), { ssr: false });
  37. const ForbiddenPage = dynamic(() => import('~/components/ForbiddenPage'), { ssr: false });
  38. type Props = CommonProps & {
  39. shareLinkRelatedPage?: IShareLinkRelatedPage,
  40. shareLink?: IShareLinkHasId,
  41. isExpired: boolean,
  42. disableLinkSharing: boolean,
  43. isSearchServiceConfigured: boolean,
  44. isSearchServiceReachable: boolean,
  45. isSearchScopeChildrenAsDefault: boolean,
  46. drawioUri: string | null,
  47. rendererConfig: RendererConfig,
  48. };
  49. type IShareLinkRelatedPage = IPagePopulatedToShowRevision & PageDocument;
  50. superjson.registerCustom<IShareLinkRelatedPage, string>(
  51. {
  52. isApplicable: (v): v is IShareLinkRelatedPage => {
  53. return v != null
  54. && v.toObject != null
  55. && v.lastUpdateUser != null
  56. && v.creator != null
  57. && v.revision != null;
  58. },
  59. serialize: (v) => { return superjson.stringify(v.toObject()) },
  60. deserialize: (v) => { return superjson.parse(v) },
  61. },
  62. 'IShareLinkRelatedPageTransformer',
  63. );
  64. // GrowiContextualSubNavigation for shared page
  65. // get page info from props not to send request 'GET /page' from client
  66. type GrowiContextualSubNavigationForSharedPageProps = {
  67. currentPage?: IPagePopulatedToShowRevision,
  68. isLinkSharingDisabled: boolean,
  69. }
  70. const GrowiContextualSubNavigationForSharedPage = (props: GrowiContextualSubNavigationForSharedPageProps): JSX.Element => {
  71. const { currentPage, isLinkSharingDisabled } = props;
  72. if (currentPage == null) { return <></> }
  73. return (
  74. <div data-testid="grw-contextual-sub-nav">
  75. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  76. </div>
  77. );
  78. };
  79. const SharedPage: NextPageWithLayout<Props> = (props: Props) => {
  80. useCurrentPathname(props.shareLink?.relatedPage.path);
  81. useIsSearchPage(false);
  82. useShareLinkId(props.shareLink?._id);
  83. useCurrentPageId(props.shareLink?.relatedPage._id);
  84. useCurrentUser(props.currentUser);
  85. useRendererConfig(props.rendererConfig);
  86. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  87. useIsSearchServiceReachable(props.isSearchServiceReachable);
  88. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  89. useDrawioUri(props.drawioUri);
  90. useIsContainerFluid(props.isContainerFluid);
  91. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName();
  92. const isNotFound = props.shareLink == null || props.shareLink.relatedPage == null || props.shareLink.relatedPage.isEmpty;
  93. const isShowSharedPage = !props.disableLinkSharing && !isNotFound && !props.isExpired;
  94. const shareLink = props.shareLink;
  95. const pagePath = props.shareLinkRelatedPage?.path ?? '';
  96. const revisionBody = props.shareLinkRelatedPage?.revision.body;
  97. const title = generateCustomTitleForPage(props, pagePath);
  98. const rendererOptions = generateSSRViewOptions(props.rendererConfig, pagePath);
  99. const ssrBody = <RevisionRenderer rendererOptions={rendererOptions} markdown={revisionBody ?? ''} />;
  100. const sideContents = shareLink != null
  101. ? <PageSideContents page={shareLink.relatedPage} />
  102. : <></>;
  103. // const footerContents = shareLink != null && isPopulated(shareLink.relatedPage.revision)
  104. // ? (
  105. // <>
  106. // <Comments pageId={shareLink._id} pagePath={shareLink.relatedPage.path} revision={shareLink.relatedPage.revision} />
  107. // </>
  108. // )
  109. // : <></>;
  110. const contents = (() => {
  111. const ShareLinkPageContents = dynamic<ShareLinkPageContentsProps>(
  112. () => import('~/components/ShareLink/ShareLinkPageContents').then(mod => mod.ShareLinkPageContents),
  113. {
  114. ssr: false,
  115. loading: () => ssrBody,
  116. },
  117. );
  118. return <ShareLinkPageContents page={props.shareLinkRelatedPage} />;
  119. })();
  120. return (
  121. <>
  122. <Head>
  123. <title>{title}</title>
  124. </Head>
  125. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  126. <header className="py-0 position-relative">
  127. {isShowSharedPage
  128. && <GrowiContextualSubNavigationForSharedPage currentPage={props.shareLinkRelatedPage} isLinkSharingDisabled={props.disableLinkSharing} />}
  129. </header>
  130. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  131. <MainPane
  132. sideContents={sideContents}
  133. // footerContents={footerContents}
  134. >
  135. { props.disableLinkSharing && (
  136. <div className="mt-4">
  137. <ForbiddenPage isLinkSharingDisabled={props.disableLinkSharing} />
  138. </div>
  139. )}
  140. { (isNotFound && !props.disableLinkSharing) && (
  141. <div className="container-lg">
  142. <h2 className="text-muted mt-4">
  143. <i className="icon-ban" aria-hidden="true" />
  144. <span> Page is not found</span>
  145. </h2>
  146. </div>
  147. )}
  148. { (props.isExpired && !props.disableLinkSharing && shareLink != null) && (
  149. <div className="container-lg">
  150. <ShareLinkAlert expiredAt={shareLink.expiredAt} createdAt={shareLink.createdAt} />
  151. <h2 className="text-muted mt-4">
  152. <i className="icon-ban" aria-hidden="true" />
  153. <span> Page is expired</span>
  154. </h2>
  155. </div>
  156. )}
  157. {(isShowSharedPage && shareLink != null) && (
  158. <>
  159. <ShareLinkAlert expiredAt={shareLink.expiredAt} createdAt={shareLink.createdAt} />
  160. <div className="mb-5">
  161. { contents }
  162. </div>
  163. </>
  164. )}
  165. </MainPane>
  166. </div>
  167. </>
  168. );
  169. };
  170. SharedPage.getLayout = function getLayout(page) {
  171. return (
  172. <>
  173. <DrawioViewerScript />
  174. <ShareLinkLayout>{page}</ShareLinkLayout>
  175. </>
  176. );
  177. };
  178. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  179. const req: CrowiRequest = context.req as CrowiRequest;
  180. const { crowi } = req;
  181. const { configManager, searchService, xssService } = crowi;
  182. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  183. props.isSearchServiceConfigured = searchService.isConfigured;
  184. props.isSearchServiceReachable = searchService.isReachable;
  185. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  186. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  187. props.rendererConfig = {
  188. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  189. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  190. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  191. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  192. plantumlUri: process.env.PLANTUML_URI ?? null,
  193. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  194. // XSS Options
  195. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  196. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  197. attrWhiteList: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  198. tagWhiteList: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  199. highlightJsStyleBorder: configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  200. };
  201. }
  202. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  203. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  204. props._nextI18Next = nextI18NextConfig._nextI18Next;
  205. }
  206. function getAction(props: Props): SupportedActionType {
  207. let action: SupportedActionType;
  208. if (props.isExpired) {
  209. action = SupportedAction.ACTION_SHARE_LINK_EXPIRED_PAGE_VIEW;
  210. }
  211. else if (props.shareLink == null) {
  212. action = SupportedAction.ACTION_SHARE_LINK_NOT_FOUND;
  213. }
  214. else {
  215. action = SupportedAction.ACTION_SHARE_LINK_PAGE_VIEW;
  216. }
  217. return action;
  218. }
  219. async function addActivity(context: GetServerSidePropsContext, action: SupportedActionType): Promise<void> {
  220. const req: CrowiRequest = context.req as CrowiRequest;
  221. const parameters = {
  222. ip: req.ip,
  223. endpoint: req.originalUrl,
  224. action,
  225. user: req.user?._id,
  226. snapshot: {
  227. username: req.user?.username,
  228. },
  229. };
  230. await req.crowi.activityService.createActivity(parameters);
  231. }
  232. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  233. const req = context.req as CrowiRequest<IUserHasId & any>;
  234. const { crowi, params } = req;
  235. const result = await getServerSideCommonProps(context);
  236. if (!('props' in result)) {
  237. throw new Error('invalid getSSP result');
  238. }
  239. const props: Props = result.props as Props;
  240. try {
  241. const ShareLinkModel = crowi.model('ShareLink');
  242. const shareLink = await ShareLinkModel.findOne({ _id: params.linkId }).populate('relatedPage');
  243. if (shareLink != null) {
  244. props.shareLinkRelatedPage = await shareLink.relatedPage.populateDataToShowRevision();
  245. props.isExpired = shareLink.isExpired();
  246. props.shareLink = shareLink.toObject();
  247. }
  248. }
  249. catch (err) {
  250. logger.error(err);
  251. }
  252. injectServerConfigurations(context, props);
  253. await injectNextI18NextConfigurations(context, props);
  254. await addActivity(context, getAction(props));
  255. return {
  256. props,
  257. };
  258. };
  259. export default SharedPage;